package admin

import (
	"beego/models"
	"errors"
	"github.com/astaxie/beego"
	"io"
	"math/rand"
	"os"
	"path"
	"strconv"
)

type BaseController struct {
	beego.Controller
}

// 图片上传
func (c *BaseController) UploadImg(picName string) (string, error) {
	//1、获取上传的文件
	f, h, err := c.GetFile(picName)
	if err != nil {
		return "", err
	}
	//2、关闭文件流
	defer f.Close()
	//3、获取后缀名 判断类型是否正确  .jpg .png .gif .jpeg
	extName := path.Ext(h.Filename)

	allowExtMap := map[string]bool{
		".jpg":  true,
		".png":  true,
		".gif":  true,
		".jpeg": true,
	}

	if _, ok := allowExtMap[extName]; !ok {
		return "", errors.New("图片后缀名不合法")
	}
	//4、创建图片保存目录  static/upload/20200623
	day := models.GetDay()
	dir := "/static/upload/" + day

	if err := os.MkdirAll(dir, 0666); err != nil {
		return "", err
	}
	//5、生成文件名称   144325235235.png
	fileUnixName := strconv.FormatInt(models.GetUnixNano(), 10)
	fileName := rand.Intn(1000)
	//static/upload/20200623/144325235235.png
	saveDir := path.Join(dir, fileUnixName+strconv.FormatInt(int64(fileName), 10)+extName)
	//6、保存图片
	_ = c.SaveToFile(picName, saveDir)
	return saveDir, nil
}

//多图上传
func (c *BaseController) UploadImgs(picName string) (int, string, error, []string) {
	files, _ := c.GetFiles(picName)
	sliceImg := make([]string, 0)
	for i, _ := range files {
		if files[i] == nil {
			sliceImg = append(sliceImg, "false")
			continue
		}
		//for each fileheader, get a handle to the actual file
		file, err := files[i].Open()
		defer file.Close()
		if err != nil {
			return -1, "文件流关闭失败", err, nil
		}

		//3、获取后缀名 判断类型是否正确  .jpg .png .gif .jpeg
		extName := path.Ext(files[i].Filename)
		if files[i].Size == 0 {
			beego.Info(files[i])
			sliceImg = append(sliceImg, "false1")
			continue
		}
		allowExtMap := map[string]bool{
			".jpg":  true,
			".png":  true,
			".gif":  true,
			".jpeg": true,
		}
		if _, ok := allowExtMap[extName]; !ok {
			return -1, "文件名后缀不正确", err, nil
		}

		//4、创建图片保存目录  static/upload/20200623
		day := models.GetDay()
		dir := "static/upload/" + day
		if err := os.MkdirAll(dir, 0666); err != nil {
			return -1, "图片目录创建失败", err, nil
		}

		//5、生成文件名称   144325235235.png
		fileUnixName := strconv.FormatInt(models.GetUnixNano(), 10)
		fileName := rand.Intn(1000)

		//static/upload/20200623/1443252352351231541100.png
		saveDir := path.Join(dir, fileUnixName+strconv.FormatInt(int64(fileName), 10)+extName)

		//create destination file making sure the path is writeable.
		dst, err := os.Create(saveDir)
		defer dst.Close()

		if err != nil {
			return -1, "文件流关闭失败1", err, nil
		}

		//copy the uploaded file to the destination file
		if _, err := io.Copy(dst, file); err != nil {
			beego.Info("error3")
			return -1, "io文件流读取失败", err, nil
		}
		sliceImg = append(sliceImg, saveDir)
	}
	return 200, "", nil, sliceImg
}
